package com.work.game.ad;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationBaseManager;
import com.work.game.ad.inter.RewardAdCallbackInter;
import com.work.game.config.UrlConfig;

import com.work.game.home.ui.model.vo.AdRecordVo;
import com.work.game.home.ui.model.vo.BaseVo;
import com.work.game.volley.BaseFragment;
import com.work.game.volley.state.HUCState;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class MediationRewardAdCallback {
    private String orderId;

    private BaseFragment baseFragment;
    private RewardAdCallbackInter rewardAdCallbackInter;
    private String codeId;
    private String userId;
    private String timeInterval;
    private String token;
    //广告对象
    private TTRewardVideoAd ttRewardVideoAd;

    private AlertDialog alertDialog;

    public static String TAG = "TAGTTRewardVideoAd";

    public MediationRewardAdCallback() {
    }

    public static volatile MediationRewardAdCallback instance;

    public static synchronized MediationRewardAdCallback getInstance() {
        if (ObjectUtil.isNull(instance)) {
            synchronized (MediationRewardAdCallback.class) {
                if (ObjectUtil.isNull(instance)) {
                    instance = new MediationRewardAdCallback();
                }
            }
        }
        return instance;
    }

    public void init(BaseFragment baseFragment, RewardAdCallbackInter rewardAdCallbackInter, String codeId, String userId, String timeInterval, String token) {
        this.baseFragment = baseFragment;
        this.rewardAdCallbackInter = rewardAdCallbackInter;
        this.codeId = codeId;
        this.userId = userId;
        this.timeInterval = timeInterval;
        this.token = token;
    }

    public void setAlertDialog(AlertDialog alertDialog) {
        this.alertDialog = alertDialog;
    }

    private AdSlot buildRewardAdlost() {
        orderId = UUID.randomUUID().toString().replace("-", "");
        return new AdSlot.Builder().setCodeId(codeId)  //广告位ID
                .setAdCount(2).setUserID(userId).setOrientation(TTAdConstant.VERTICAL)  //激励视频方向
                .setMediationAdSlot(new MediationAdSlot.Builder().setExtraObject(MediationConstant.KEY_GROMORE_EXTRA, orderId).build()).build();
    }

    //加载激励视频
    public void loadRewardAd() {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(baseFragment.getActivity());
        /** 这里为激励视频的简单功能，如需使用复杂功能，如gromore的服务端奖励验证，请参考demo中的AdUtils.kt类中激励部分 */
        adNativeLoader.loadRewardVideoAd(buildRewardAdlost(), new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int errorCode, String errorMsg) {
                //广告加载失败
                Log.i(TAG, "缓存失败errorCode:" + errorCode + ", errMsg: " + errorMsg);
            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                //广告加载失败
            }

            @Override
            public void onRewardVideoCached() {
                //广告缓存成功 此api已经废弃，请使用onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd)
            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                getInstance().ttRewardVideoAd = ttRewardVideoAd;
                Log.d(TAG, "缓存成功激励视频");
            }
        });
    }

    //展示激励视频
    public void showRewardAd() {
        if (ttRewardVideoAd == null) {
            loadReward();
            Log.i(TAG, "重新加载广告");
            return;
        }
        //验证有效时间 start
        Long endTime = System.currentTimeMillis();
        long startTime = 0L;
        String startCurrentTimeMillis = baseFragment.getSharedPreferences("startCurrentTimeMillis");
        if (StrUtil.isNotEmpty(startCurrentTimeMillis)) {
            startTime = Long.parseLong(startCurrentTimeMillis);
        }
        long time = (endTime - startTime) / 1000;
        if (time < Long.parseLong(timeInterval)) {
            alertDialog.dismiss();
            baseFragment.showToast((Long.parseLong(timeInterval) - time) + "秒后有奖励！");
            return;
        }
        ttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
            @Override
            public void onAdShow() {
                //广告展示
                //获取展示广告相关信息，需要再show回调之后进行获取
                MediationBaseManager manager = ttRewardVideoAd.getMediationManager();
                if (manager != null && manager.getShowEcpm() != null) {
                    MediationAdEcpmInfo showEcpm = manager.getShowEcpm();
                    String ecpm = showEcpm.getEcpm(); //展示广告的价格
                    String sdkName = showEcpm.getSdkName();  //展示广告的adn名称
                    String slotId = showEcpm.getSlotId(); //展示广告的代码位ID
                    AdRecordVo adRecordVo = new AdRecordVo();
                    adRecordVo.setArTransId(orderId);
                    adRecordVo.setEcpm(ecpm);
                    adRecordVo.setToken(token);
                    adRecordVo.setArChannel(sdkName);
                    adRecordVo.setArMediationRit(slotId);
                    baseFragment.hucRequestInterfase.executeStr(baseFragment, null, HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.URL_AD_RECORD, baseFragment.hucParameInterfase.getRequestParameter(adRecordVo), true);
                }
            }

            @Override
            public void onAdVideoBarClick() {
                //广告点击
            }

            @Override
            public void onAdClose() {
                //广告关闭
                rewardAdCallbackInter.rewardAdCallback(orderId);
                onDestroy();
                loadRewardAd();
            }

            @Override
            public void onVideoComplete() {
                //广告视频播放完成
            }

            @Override
            public void onVideoError() {
                //广告视频错误
            }

            @Override
            public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
                //奖励发放 已废弃 请使用 onRewardArrived 替代
            }

            @Override
            public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
            }

            @Override
            public void onSkippedVideo() {
            }
        });
        if (ttRewardVideoAd.getMediationManager().isReady()) {
            alertDialog.dismiss();
            ttRewardVideoAd.showRewardVideoAd(baseFragment.getActivity()); //展示激励视频
            baseFragment.setSharedPreferences("startCurrentTimeMillis", String.valueOf(System.currentTimeMillis()));
        } else {
            loadReward();
        }
    }

    //加载激励视频
    private void loadReward() {
        //广告缓存成功 在此回调中进行广告展示
        Long endTime = System.currentTimeMillis();
        long startTime = 0L;
        String startCurrentTimeMillis = baseFragment.getSharedPreferences("startCurrentTimeMillis");
        if (StrUtil.isNotEmpty(startCurrentTimeMillis)) {
            startTime = Long.parseLong(startCurrentTimeMillis);
        }
        long time = (endTime - startTime) / 1000;
        if (time < Long.parseLong(timeInterval)) {
            alertDialog.dismiss();
            baseFragment.showToast((Long.parseLong(timeInterval) - time) + "秒后有奖励！");
            return;
        }

        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(baseFragment.getActivity());
        /** 这里为激励视频的简单功能，如需使用复杂功能，如gromore的服务端奖励验证，请参考demo中的AdUtils.kt类中激励部分 */
        adNativeLoader.loadRewardVideoAd(buildRewardAdlost(), new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int errorCode, String errorMsg) {
                //广告加载失败
                alertDialog.dismiss();
                Toast.makeText(baseFragment.getContext(), "视频加载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                //广告加载失败
            }

            @Override
            public void onRewardVideoCached() {
                //广告缓存成功 此api已经废弃，请使用onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd)
            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                showRewardAd(baseFragment.getActivity(), ttRewardVideoAd);
                baseFragment.setSharedPreferences("startCurrentTimeMillis", String.valueOf(System.currentTimeMillis()));
            }
        });
    }

    //展示激励视频
    private void showRewardAd(Activity act, TTRewardVideoAd ttRewardVideoAd) {
        if (act == null || ttRewardVideoAd == null) {
            return;
        }
        ttRewardVideoAd.setRewardPlayAgainController(new TTRewardVideoAd.RewardAdPlayAgainController() {
            @Override
            public void getPlayAgainCondition(int i, Callback callback) {

            }
        });
        ttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
            @Override
            public void onAdShow() {
                //广告展示
                //获取展示广告相关信息，需要再show回调之后进行获取
                MediationBaseManager manager = ttRewardVideoAd.getMediationManager();
                if (manager != null && manager.getShowEcpm() != null) {
                    MediationAdEcpmInfo showEcpm = manager.getShowEcpm();
                    String ecpm = showEcpm.getEcpm(); //展示广告的价格
                    String sdkName = showEcpm.getSdkName();  //展示广告的adn名称
                    String slotId = showEcpm.getSlotId(); //展示广告的代码位ID
                    AdRecordVo adRecordVo = new AdRecordVo();
                    adRecordVo.setArTransId(orderId);
                    adRecordVo.setEcpm(ecpm);
                    adRecordVo.setToken(token);
                    adRecordVo.setArChannel(sdkName);
                    adRecordVo.setArMediationRit(slotId);
                    baseFragment.hucRequestInterfase.executeStr(baseFragment, null, HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.URL_AD_RECORD, baseFragment.hucParameInterfase.getRequestParameter(adRecordVo), true);
                }
            }

            @Override
            public void onAdVideoBarClick() {
                //广告点击
            }

            @Override
            public void onAdClose() {
                //广告关闭
                rewardAdCallbackInter.rewardAdCallback(orderId);
                onDestroy();
                loadRewardAd();
            }

            @Override
            public void onVideoComplete() {
                //广告视频播放完成
            }

            @Override
            public void onVideoError() {
                //广告视频错误
            }

            @Override
            public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
                //奖励发放 已废弃 请使用 onRewardArrived 替代
            }

            @Override
            public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
            }

            @Override
            public void onSkippedVideo() {
            }
        });
        alertDialog.dismiss();
        ttRewardVideoAd.showRewardVideoAd(act); //展示激励视频
    }

    //激励视频 end
    private void onDestroy() {
        if (ttRewardVideoAd != null && ttRewardVideoAd.getMediationManager() != null) {
            ttRewardVideoAd.getMediationManager().destroy();
        }
        ttRewardVideoAd = null;
    }
}
